package com.remeberword;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class BackupRestoreActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backup_restore);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.show_word:
                        startActivity(new Intent(BackupRestoreActivity.this, MainActivity.class));
                        break;
                    case R.id.freq_manager:
                        startActivity(new Intent(BackupRestoreActivity.this, WordManageActivity.class));
                        break;
                    case R.id.word_add:
                        startActivity(new Intent(BackupRestoreActivity.this, AddWordActivity.class));
                        break;
                }
                mDrawerLayout.closeDrawers();
                return true;
            }
        });
        Button backupButton = (Button) findViewById(R.id.backup);
        backupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(BackupRestoreActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(BackupRestoreActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    backup();
                }
            }
        });
        Button restoreButton = (Button) findViewById(R.id.restore);
        restoreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(BackupRestoreActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(BackupRestoreActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
                } else {
                    restore();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == 1)
                backup();
            else if (requestCode == 2)
                restore();
        } else
            Toast.makeText(this, "请开启SD卡写入权限", Toast.LENGTH_SHORT).show();
    }

    private void backup() {
        if (! isExternalStorageWritable())
            return;
        String data;
        FileOutputStream out = null;
        BufferedWriter writer = null;
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "WordPair.db", null);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select english, chinese, frequency from wordPair order by frequency desc", new String[]{});

        File f = null;

        try {
            if (cursor.moveToFirst()) {
                f = Environment.getExternalStoragePublicDirectory("/Backup.txt");;
                out = new FileOutputStream(f);
                writer = new BufferedWriter(new OutputStreamWriter(out));
                do {
                    String english = cursor.getString(cursor.getColumnIndex("english"));
                    String chinese = cursor.getString(cursor.getColumnIndex("chinese"));
                    int frequency = cursor.getInt(cursor.getColumnIndex("frequency"));
                    data = english + "\t" + chinese + "\t" + frequency;
                    writer.write(data);
                    writer.newLine();
                } while (cursor.moveToNext());
                AlertDialog.Builder dialog = new AlertDialog.Builder(BackupRestoreActivity.this);
                dialog.setMessage("备份完成 文件存储至" + f.getAbsolutePath());
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                dialog.show();
            } else {
                AlertDialog.Builder dialog = new AlertDialog.Builder(BackupRestoreActivity.this);
                dialog.setMessage("无单词可备份");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                dialog.show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cursor.close();
            try {
                if (writer != null)
                    writer.close();
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void restore() {
        new RestoreTask(BackupRestoreActivity.this).execute();
        /*final ProgressDialog progressDialog = new ProgressDialog(BackupRestoreActivity.this);
        progressDialog.setMessage("恢复中");
        progressDialog.setCancelable(false);
        progressDialog.show();

        FileInputStream in = null;
        BufferedReader reader = null;
        MyDatabaseHelper dbHelper;
        SQLiteDatabase db;
        try {
            File f = Environment.getExternalStoragePublicDirectory("/Backup.txt");
            in = new FileInputStream(f);
            reader = new BufferedReader(new InputStreamReader(in));
            dbHelper = new MyDatabaseHelper(this, "WordPair.db", null);
            db = dbHelper.getWritableDatabase();

//        Runnable progressRunnable = new Runnable() {
//
//            @Override
//            public void run() {
//                progressDialog.dismiss();
//            }
//        };
//        Handler pdCanceller = new Handler();
//        pdCanceller.postDelayed(progressRunnable, 2000);

            Map<String, List> en_ch = new HashMap<>();
            Cursor cursor = db.rawQuery("select * from wordPair", new String[]{});
            if (cursor.moveToFirst()) {
                en_ch = new HashMap<>();
                do {
                    String english = cursor.getString(cursor.getColumnIndex("english"));
                    String chinese = cursor.getString(cursor.getColumnIndex("chinese"));

                    // 拆中文
                    String[] chs = chinese.split("；");
                    List<String> list = new ArrayList<>();
                    for (String s : chs)
                        list.add(s);

                    en_ch.put(english, list);
                } while (cursor.moveToNext());
            }

            String line;
            while ((line = reader.readLine()) != null) {
                String[] strs = line.split("\t");
                String english = strs[0];
                String chinese = strs[1];

                if (en_ch.size() > 0 && en_ch.containsKey(english)) { // 单词本中有这个词
                    List<String> list = en_ch.get(english);
                    StringBuilder sb = new StringBuilder();

                    sb.append(list.get(0));
                    for (int i = 1; i < list.size(); i++)
                        sb.append("；" + list.get(i));
                    if (!list.contains(chinese)) //已有此中文解释
                        sb.append("；" + chinese);
                    chinese = sb.toString();

                    db.execSQL("update WordPair set frequency = frequency + 1, chinese = ? where english = ?",
                            new String[]{chinese, english});
                } else { // 单词本中无这个词
                    db.execSQL("insert into WordPair(english, chinese, frequency) values(?, ?, ?)",
                            new String[]{strs[0], strs[1], strs[2]});

                    // 拆中文
                    String[] chs = strs[1].split("；");
                    List<String> list = new ArrayList<>();
                    for (String s : chs)
                        list.add(s);

                    en_ch.put(strs[0], list);
                }
                cursor.close();
            }
            en_ch.clear();
            progressDialog.dismiss();
//            Toast.makeText(BackupRestoreActivity.this, "恢复完成", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            if (e instanceof FileNotFoundException)
                Toast.makeText(BackupRestoreActivity.this, "找不到备份文件", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("备份恢复");
    }

    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }
}
